package com.service;


import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

//import org.redisson.api.RedissonClient;

@Service
public class MiaoSha {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    public static AtomicInteger count = null;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 使用锁的方式
     */
    public void lock() {
        RLock rLock = redissonClient.getLock("miaosha");
        rLock.lock();
        int goods = (Integer) redisTemplate.boundValueOps("goods").get();
        if (goods > 0) {
            goods--;
            redisTemplate.boundValueOps("goods").set(goods);
        }
        rLock.unlock();
    }


    /**
     * 不使用锁的方式
     */
    public void unlock() {
        int goods = (Integer) redisTemplate.boundValueOps("goods").get();
        if (count == null)
            count = new AtomicInteger(goods);
        if (goods > 0) {
            int newgoods = count.decrementAndGet();
            System.out.println(newgoods);
            redisTemplate.boundValueOps("goods").set(newgoods);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService es = Executors.newFixedThreadPool(100);
        for (int i=1;i<=1000;i++)
        {
            //开启多线程
            es.execute(new Runnable() {
                @Override
                public void run() {
                   gogo();
                }
            });
        }
        es.shutdown();
        es.awaitTermination(1, TimeUnit.MINUTES);
        System.out.println("done!:"+c);
    }

    static int c = 0;
    static AtomicInteger ai = new AtomicInteger(c);
    static void gogo()
    {
       c = ai.incrementAndGet();
    }

}
